#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   DeviceAddDialog.py
@Time    :   2020/07/17 14:23:09
@Author  :   Xiong qiufeng
@Version :   1.0
@Contact :   1528399071@qq.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
'''

import os
import copy
import json
from collections import OrderedDict

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.mqttSet import Ui_Dialog
from common.libs.Helper import generateUUID

CONFIG_PATH = os.getcwd()+'/conf/mqtt_set.json'

class MqttSetDialog(QDialog, Ui_Dialog):

    config = {}

    def __init__(self,parent=None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Mqtt服务器连接设置")
        self.pushButton_clientid_generate.clicked.connect(lambda:self.lineEdit_clientid.setText('PC-'+generateUUID()[0:8]))
        self.pushButton_save.clicked.connect(self.accept)
        self.pushButton_cancel.clicked.connect(self.reject)
        self.load()

    def readConfig(self):
        """读取配置文件"""
        try:
            with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
                self.config = json.loads(f.read(), object_pairs_hook=OrderedDict)
            return True
        except Exception as e:
            logger.info(e)
            QMessageBox.information(self,"提示","读取配置文件失败！", QMessageBox.Yes)
            return False

    def writeConfig(self):
        save = json.dumps(self.config, indent=4)
        try:
            with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
                f.write(save)
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
        except Exception as e:
            QMessageBox.information(self,"提示","保存失败:\r\n%s"%e, QMessageBox.Yes)

    def load(self):
        if self.readConfig():
            conf = self.config
            self.lineEdit_host.setText(conf['host'])
            self.spinBox_port.setValue(int(conf['port']))
            self.lineEdit_clientid.setText(conf['client_id'])
            self.spinBox_timeout.setValue(int(conf['timeout']))
            self.spinBox_keep_alive.setValue(int(conf['keep_alive']))
            self.checkBox_auto_connect.setChecked(conf['auto_connect'])

    def save(self):
        self.config['host'] = self.lineEdit_host.text()
        self.config['port'] = self.spinBox_port.value()
        self.config['client_id'] = self.lineEdit_clientid.text()
        self.config['timeout'] = self.spinBox_timeout.value()
        self.config['keep_alive'] = self.spinBox_keep_alive.value()
        self.config['auto_connect'] = self.checkBox_auto_connect.isChecked()
        self.writeConfig()

    def show(self):
        self.load()
        QDialog.show(self)

    def accept(self):
        self.save()
        QDialog.accept(self)

    def reject(self):
        QDialog.reject(self)